<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/4
 * Time: 15:02
 */
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;

use Illuminate\Support\Facades\Request;
use DB;
use \Illuminate\Support\Facades\Input;
use App\ModelStatistic\StatisticCommon;

class AreaFormReal extends Model{
    public static function paginate()
    {
        $accout = Request::get('account');
        $perPage = Request::get('per_page', 20);
        $page = Request::get('page', 1);
        $created_time = Request::get('created_time');

        $start = ($page-1)*$perPage;

        $tableAccount = 'platsdk_order';
        $rw = \DB::connection('mysql_bgac')->table($tableAccount)->select('cp_area',DB::raw('sum(tb_recharge_price.deal) as sum_deal, sum(tb_recharge_price.dollar) as sum_dollar,sum(tb_recharge_price.rmb) as sum_rmb , sum(1) as ChargeNo'))
        ->leftJoin('recharge_price', 'platsdk_order.cp_product_id', '=', 'recharge_price.recharge_id')
        ->groupby('cp_area');
        self::SourceCondition($rw);
        $total = $rw->get()->count();
        $rw = $rw->skip($start)->take($perPage);
        $data = $rw->get();
        $data = $data->toArray();
//        var_dump($data);exit();

        foreach ($data as &$obj) {
            $obj->sumMoney = round($obj->sumMoney / 100, 2);
        }
        // $data = json_decode($data, true);
        \Log::debug(__METHOD__, [$rw->toSql()]);
        $list = static::hydrate($data);

        $paginator = new LengthAwarePaginator($list, $total, $perPage);

        $paginator->setPath(url()->current());
//var_dump($paginator);exit();
        return $paginator;
    }

    //
    
    public static function SourceCondition(&$rw)
    {
        $cond = Request::all();
        if ($cond['OrderSerial']){
            $rw->where("OrderSerial", 'like', $cond["OrderSerial"].'%');
        }

        $cond["charge_ok"] = Input::get("charge_ok", 1);
        if ($cond["charge_ok"]){
            $rw->where("OrderSerial", "<>", "");
        }

        $cond["cp_area"] = intval(Input::get("cp_area", 0));
        \Log::debug(__METHOD__, [$cond['cp_area']]);
        if ($cond["cp_area"] ){
            $rw->where("cp_area", "=", $cond['cp_area'] == -1 ? 0 : $cond['cp_area'] );
        }

        $created_time = Request::get('created_time', []);
        $created_time['start'] = $created_time['start'] ?: strtotime(date('Y-m-d',time()));
        if ($created_time['start']) {
            $rw->where('created_time', ">=", StatisticCommon::GetIntTime($created_time['start']) );
        }

        if ($created_time['end']) {
            $rw->where('created_time', "<=", StatisticCommon::GetIntTime($created_time['end']) );
        }

        \Log::debug('order list area created_time', [StatisticCommon::GetIntTime($created_time['start'])]);
    }


}